<template>
  <div>
    <div>
      <div class="header_con">
        <div class="header">
          <div class="welcome fl">欢迎来到美多商城!</div>
          <div class="fr">
            <div class="login_btn fl">
              欢迎您：<em>{{ username }}</em>
              <span>|</span>
              <a @click="logout">退出</a>
            </div>
            <div class="user_link fl">
              <span>|</span>
              <a href="user_center_info.html">用户中心</a>
              <span>|</span>
              <a href="cart.html">我的购物车</a>
              <span>|</span>
              <a href="user_center_order.html">我的订单</a>
            </div>
          </div>
        </div>
      </div>

      <div class="search_bar clearfix">
        <a
          href="index.html"
          class="logo fl"
        ><img src="/static/images/logo.png"></a>
        <div class="sub_page_name fl">|&nbsp;&nbsp;&nbsp;&nbsp;用户中心</div>
        <form
          method="get"
          action="/search.html"
          class="search_con fr mt40"
        >
          <input
            type="text"
            class="input_text fl"
            name="q"
            placeholder="搜索商品"
          >
          <input
            type="submit"
            class="input_btn fr"
            name=""
            value="搜索"
          >
        </form>
      </div>

      <div class="main_con clearfix">
        <div class="left_menu_con clearfix">
          <h3>用户中心</h3>
          <ul>
            <li><a href="UserCenter">· 个人信息</a></li>
            <li><a href="user_center_order.html">· 全部订单</a></li>
            <li><a
                href="user_center_site.html"
                class="active"
              >· 收货地址</a></li>
            <li><a href="user_center_pass.html">· 修改密码</a></li>
          </ul>
        </div>
        <div class="right_content clearfix">
          <div class="site_top_con">
            <a @click="show_add">新增收货地址</a>
            <span>您已创建了<b>{{addresses.length}}</b>个收货地址，最多可创建<b>{{ limit }}</b>个</span>
          </div>
          <div
            class="site_con"
            v-for="(address, index) in addresses"
            :key="address.id"
          >
            <div class="site_title">
              <div v-if="is_set_title[index]">
                <input
                  v-model="input_title"
                  type="text"
                  name=""
                >
                <input
                  @click="save_title(index)"
                  type="button"
                  name=""
                  value="保 存"
                >
                <input
                  @click="cancel_title(index)"
                  type="reset"
                  name=""
                  value="取 消"
                >
              </div>
              <div v-else>
                <h3>{{ address.title }}</h3>
                <a @click="show_edit_title(index)"></a>
              </div>
              <em
                v-if="address.id==default_address_id"
              >默认地址</em>
              <span @click="del_address(index)">×</span>
            </div>
            <ul class="site_list">
              <li><span>收货人：</span><b>{{ address.receiver }}</b></li>
              <li><span>所在地区：</span><b>{{ address.province_name }} {{address.city_name}} {{ address.district_name }}</b></li>
              <li><span>地址：</span><b>{{ address.place }}</b></li>
              <li><span>手机：</span><b>{{ address.mobile }}</b></li>
              <li><span>固定电话：</span><b>{{ address.tel }}</b></li>
              <li><span>电子邮箱：</span><b>{{ address.email }}</b></li>
            </ul>
            <div class="down_btn">
              <a
                v-if="address.id!=default_address_id"
                @click="set_default(index)"
              >设为默认</a>
              <a @click="show_edit(index)">编辑</a>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="foot_link">
          <a href="#">关于我们</a>
          <span>|</span>
          <a href="#">联系我们</a>
          <span>|</span>
          <a href="#">招聘人才</a>
          <span>|</span>
          <a href="#">友情链接</a>
        </div>
        <p>CopyRight © 2016 北京美多商业股份有限公司 All Rights Reserved</p>
        <p>电话：010-****888 京ICP备*******8号</p>
      </div>

      <div
        class="pop_con"
        v-show="is_show_edit"
      >
        <div class="site_con site_pop">
          <div class="site_pop_title">
            <h3 v-if="editing_address_index">编辑收货地址</h3>
            <h3 v-else>新增收货地址</h3>
            <a @click="is_show_edit=false">×</a>
          </div>
          <form>
            <div class="form_group">
              <label>*收货人：</label>
              <input
                v-model="form_address.receiver"
                @blur="check_receiver"
                type="text"
                name=""
              >
              <span
                v-show="error_receiver"
                class="error_tip"
              >请填写收件人</span>
            </div>
            <div class="form_group">
              <label>*所在地区：</label>
              <select v-model="form_address.province">
                <option
                  v-for="province in provinces"
                  :value="province.id"
                  :key="province.id"
                >{{ province.name }}</option>
              </select>
              <select v-model="form_address.city">
                <option
                  v-for="city in cities"
                  v-bind:value="city.id"
                  :key="city.id"
                >{{ city.name }}</option>
              </select>
              <select v-model="form_address.district">
                <option
                  v-for="district in districts"
                  v-bind:value="district.id"
                  :key="district.id"
                >{{ district.name }}</option>
              </select>
            </div>
            <div class="form_group">
              <label>*详细地址：</label>
              <input
                v-model="form_address.place"
                @blur="check_place"
                type="text"
                name=""
              >
              <span
                v-show="error_place"
                class="error_tip"
              >请填写地址信息</span>
            </div>
            <div class="form_group">
              <label>*手机：</label>
              <input
                v-model="form_address.mobile"
                @blur="check_mobile"
                type="text"
                name=""
              >
              <span
                v-show="error_mobile"
                class="error_tip"
              >手机信息有误</span>
            </div>
            <div class="form_group">
              <label>固定电话：</label>
              <input
                v-model="form_address.tel"
                type="text"
                name=""
              >
            </div>
            <!-- <div class="form_group">
              <label>邮箱：</label>
              <input
                v-model="form_address.email"
                @blur="check_email"
                type="text"
                name=""
              >
              <span
                v-show="error_email"
                class="error_tip"
              >邮箱信息有误</span>
            </div> -->
            <input
              @click="save_address"
              type="button"
              name=""
              value="保 存"
              class="info_submit"
            >
            <input
              @click="is_show_edit=false"
              type="reset"
              name=""
              value="取 消"
              class="info_submit info_reset"
            >
          </form>
        </div>
        <div class="mask"></div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios"
export default {
  data() {
    return {
      host: host,
      user_id: sessionStorage.user_id || localStorage.user_id,
      token: sessionStorage.token || localStorage.token,
      username: sessionStorage.username || localStorage.username,
      is_show_edit: false,
      provinces: [],
      cities: [],
      districts: [],
      addresses: [],
      limit: 20,  // 最多创建多少个地址
      default_address_id: localStorage.default_address_id,  // 默认地址id
      form_address: {
        receiver: '',
        province: '',
        city: '',
        district: '',
        place: '',
        mobile: '',
        tel: '',
        // email: '',
      },
      error_receiver: false,
      error_place: false,
      error_mobile: false,
      error_email: false,
      editing_address_index: '', // 正在编辑的地址在addresses中的下标，''表示新增地址
      is_set_title: [],
      input_title: ''
    }
  },
  mounted: function () {
    //http://127.0.0.1:8000/area/?parent=1 
    // 取省数据
    var params = {
      parent: 1
    }
    axios.get(this.host + '/area/',
      {
        params,
        responseType: 'json',
        headers: {
          'Authorization': 'JWT ' + this.token
        }
      }).then(response => {
        // debugger
        this.provinces = response.data.results;
      })
      .catch(error => {
        // debugger
        alert(error.response.data);
      });

    // 补充获取地址数据的请求
    // 请求参数
    // # 生成url的情况
    // # GET  http://127.0.0.1:8000/address/?user=n     过滤属于自己的地址
    // # POST http://127.0.0.1:8000/address/  body{"user":"uid","":""}    增加新地址
    // # PUT  http://127.0.0.1:8000/address/pk/  body{"":"","":""}    修改地址
    var params = {
      user: this.user_id
    }
    axios.get(this.host + '/address/', {
      params,
      headers: {
        'Authorization': 'JWT ' + this.token
      },
      responseType: 'json'
    })
      .then(response => {
        // debugger
        this.addresses = response.data.results;
      })
      .catch(error => {
        // debugger
        status = error.response.status;
        if (status == 401 || status == 403) {
          // location.href = 'login.html?next=/user_center_site.html';
        } else {
          alert(error.response.data.detail);
        }
      })
  },
  watch: {
    'form_address.province': function () {
      if (this.form_address.province) {
        var params = {
          parent: this.form_address.province
        }
        axios.get(this.host + '/area/',
          {
            params,
            responseType: 'json',
            headers: {
              'Authorization': 'JWT ' + this.token
            }
          })
          .then(response => {
            this.cities = response.data.results;
          })
          .catch(error => {
            console.log(error.response.data);
            this.cities = [];
          });
      }
    },
    'form_address.city': function () {
      if (this.form_address.city) {
        var params = {
          parent: this.form_address.city
        }
        axios.get(this.host + '/area/',
          {
            params,
            responseType: 'json',
            headers: {
              'Authorization': 'JWT ' + this.token
            }
          })
          .then(response => {
            this.districts = response.data.results;
          })
          .catch(error => {
            console.log(error.response.data);
            this.districts = [];
          });
      }
    }
  },
  methods: {
    // 退出
    logout: function () {
      sessionStorage.clear();
      localStorage.clear();
      location.href = '/login.html';
    },
    clear_all_errors: function () {
      this.error_receiver = false;
      this.error_mobile = false;
      this.error_place = false;
      this.error_email = false;
    },
    // 展示新增地址界面
    show_add: function () {
      this.clear_all_errors();
      this.editing_address_index = '';
      this.form_address.receiver = '';
      this.form_address.province = '';
      this.form_address.city = '';
      this.form_address.district = '';
      this.form_address.place = '';
      this.form_address.mobile = '';
      this.form_address.tel = '';
      this.form_address.email = '';
      this.is_show_edit = true;
    },
    // 展示编辑地址界面
    show_edit: function (index) {
      this.clear_all_errors();
      this.editing_address_index = index;
      // 只获取数据，防止修改form_address影响到addresses数据
      this.form_address = JSON.parse(JSON.stringify(this.addresses[index]));
      this.is_show_edit = true;
    },
    check_receiver: function () {
      if (!this.form_address.receiver) {
        this.error_receiver = true;
      } else {
        this.error_receiver = false;
      }
    },
    check_place: function () {
      if (!this.form_address.place) {
        this.error_place = true;
      } else {
        this.error_place = false;
      }
    },
    check_mobile: function () {
      var re = /^1[345789]\d{9}$/;
      if (re.test(this.form_address.mobile)) {
        this.error_mobile = false;
      } else {
        this.error_mobile = true;
      }
    },
    check_email: function () {
      if (this.form_address.email) {
        var re = /^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$/;
        if (re.test(this.form_address.email)) {
          this.error_email = false;
        } else {
          this.error_email = true;
        }
      }
    },

    // 保存地址
    save_address: function () {
      if (this.error_receiver || this.error_place || this.error_mobile || !this.form_address.province || !this.form_address.city || !this.form_address.district) {
        alert('信息填写有误！');
      } else {

        if (this.editing_address_index === '') {
          // 新增地址
          //# POST http://127.0.0.1:8000/address/  body{"user":"uid","":""}    增加新地址
          //form_address: {
          //   'user':24,
          //   receiver: '',
          //   province: '',
          //   city: '',
          //   district: '',
          //   place: '',
          //   mobile: '',
          //   tel: '',
          //   email: '',
          // }
          this.form_address.title = this.form_address.receiver;
          this.form_address.user = this.user_id
          axios.post(this.host + '/address/', this.form_address, {
            headers: {
              'Authorization': 'JWT ' + this.token
            },
            responseType: 'json'
          })
            .then(response => {
              // 将新地址添加到地址数组头部
              this.addresses.splice(0, 0, response.data);
              this.is_show_edit = false;
            })
            .catch(error => {
              console.log(error.response.data);
            })
        } else {
          // /address/pk/  body {}
          // 修改地址
          axios.put(this.host + '/address/' + this.addresses[this.editing_address_index].id + '/', this.form_address, {
            headers: {
              'Authorization': 'JWT ' + this.token
            },
            responseType: 'json'
          })
            .then(response => {
              this.addresses[this.editing_address_index] = response.data;
              this.is_show_edit = false;
            })
            .catch(error => {
              alert(error.response.data.detail || error.response.data.message);
            })
        }
      }
    },
    // 删除地址
    del_address: function (index) {
      // # DELETE  http://127.0.0.1:8000/address/pk/     删除地址
      axios.delete(this.host + '/address/' + this.addresses[index].id + '/', {
        headers: {
          'Authorization': 'JWT ' + this.token
        },
        responseType: 'json'
      })
        .then(response => {
          // 从数组中移除地址
          this.addresses.splice(index, 1);
        })
        .catch(error => {
          console.log(error.response.data);
        })
    },
    // 设置默认地址
    set_default: function (index) {
      //# /default_address/uid/ body{'default_address':'address_id'}
      var params = {
        'default_address': this.addresses[index].id
      }
      axios.patch(this.host + '/user/' + this.user_id + '/', params, {
        headers: {
          'Authorization': 'JWT ' + this.token
        },
        responseType: 'json'
      })
        .then(response => {
          this.default_address_id = this.addresses[index].id;
          localStorage.default_address_id = this.default_address_id
        })
        .catch(error => {
          console.log(error.response.data);
        })
    },
    // 展示编辑标题
    show_edit_title: function (index) {
      this.input_title = this.addresses[index].title;
      for (var i = 0; i < index; i++) {
        this.is_set_title.push(false);
      }
      this.is_set_title.push(true);
    },
    // 保存地址标题
    save_title: function (index) {
      if (!this.input_title) {
        alert("请填写标题后再保存！");
      } else {
        // /address_title/
        var params = {
          title: this.input_title // 新标题
        }
        axios.patch(this.host + '/address/' + this.addresses[index].id + '/', params, {
          headers: {
            'Authorization': 'JWT ' + this.token
          },
          responseType: 'json'
        })
          .then(response => {
            this.addresses[index].title = this.input_title;
            this.is_set_title = [];
          })
          .catch(error => {
            console.log(error.response.data);
          })
      }
    },
    // 取消保存地址
    cancel_title: function (index) {
      this.is_set_title = [];
    }
  }
}
</script>

<style>
</style>